package com.vizhuo.utils.baidu.map;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;

import com.vizhuo.utils.JacksonUtil;
import com.vizhuo.utils.JsonUtil;

import cn.hl.hm.util.Tools;

/**
 * @author YuanWenLong 作者 E-mail: yuanwenlong2010@163.com
 * @date 创建时间：2015年7月20日 下午12:06:08
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public class BaiDuMapUtil {

    private static final String HTTP_BAIDU_API_URL = "http://apis.baidu.com/apistore/distance/waypoints";

    private static final String HTTP_BAIDU_API_GEOCODER = "http://api.map.baidu.com/geocoder/v2/";

    /**
     * 根据百度坐标两点（经纬度），得到两点之间的直线距离（单位 ：米 M）
     * 
     * @param lat1Str
     *            起点纬度
     * @param lng1Str
     *            起点经度
     * @param lat2Str
     *            终点纬度
     * @param lng2Str
     *            终点经度
     * @return 两点之间距离（单位 ：米 M）
     */
    public static double getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {

        String httpArg = "waypoints=" + lng1Str + "%2C" + lat1Str + "%3B" + lng2Str + "%2C" + lat2Str
                + "&output=json&coord_type=bd09ll";
        String jsonResult = request(HTTP_BAIDU_API_URL, httpArg);
        // System.out.println(jsonResult);
        BaiDuAPIResult result = JacksonUtil.toObject(jsonResult, BaiDuAPIResult.class);
        // System.out.print(result.getStatus());
        Double distance = 10.0;
        if(Tools.isNotObject(result.getResults())){
        	distance=result.getResults().get(0);
        }
        // System.out.println(distance);
        return distance.doubleValue();

    }

    /**
     * 根据百度坐标两点（经纬度），得到两点之间的直线距离（单位 ：米 M）
     * 
     * @param lat1Str
     *            起点纬度
     * @param lng1Str
     *            起点经度
     * @param lat2Str
     *            终点纬度
     * @param lng2Str
     *            终点经度
     * @return 两点之间距离（单位 ：米 M）
     */
    public static double getDistanceByDouble(double lat1, double lng1, double lat2, double lng2) {

        String httpArg = "waypoints=" + lng1 + "%2C" + lat1 + "%3B" + lng2 + "%2C" + lat2
                + "&output=json&coord_type=bd09ll";
        String jsonResult = request(HTTP_BAIDU_API_URL, httpArg);
        // System.out.println(jsonResult);
        BaiDuAPIResult result = JacksonUtil.toObject(jsonResult, BaiDuAPIResult.class);
        // System.out.print(result.getStatus());
        Double distance = result.getResults().get(0);
        // System.out.println(distance);
        return distance.doubleValue();

    }

    /**
     * 根据百度坐标两点（经纬度），得到两点之间的直线距离（单位 ：米 M）
     * 
     * @param lat1Str
     *            起点经度
     * @param lng1Str
     *            起点纬度
     * @param lat2Str
     *            终点经度
     * @param lng2Str
     *            终点纬度
     * @return 两点之间距离（单位 ：米 M）
     */
    public static double getDistanceByString(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
        String httpArg = "waypoints=" + lng1Str + "%2C" + lat1Str + "%3B" + lng2Str + "%2C" + lat2Str
                + "&output=json&coord_type=bd09ll";
        String jsonResult = request(HTTP_BAIDU_API_URL, httpArg);
        // System.out.println(jsonResult);
        BaiDuAPIResult result = JacksonUtil.toObject(jsonResult, BaiDuAPIResult.class);
        // System.out.print(result.getStatus());
        Double distance = result.getResults().get(0);
        // System.out.println(distance);
        return distance.doubleValue();
    }

    private static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("apikey", "3960b4299f9110ab03e6cf041bdc4b2e");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static HashMap getAddrByBDZB(String lngStr, String latStr) {
        // 标准地址：http://api.map.baidu.com/geocoder/v2/?ak=bmN9oFwQhIAVKq7tUhdcWZ8U&callback=renderReverse&location=39.897445,116.331398&output=json&pois=0

        String httpArg = "ak=bmN9oFwQhIAVKq7tUhdcWZ8U&location=" + lngStr + "," + latStr + "&output=json&pois=0";
        String jsonResult = request(HTTP_BAIDU_API_GEOCODER, httpArg);
        // System.out.println(jsonResult);

        String status = JsonUtil.getStringValueByJsonStr(jsonResult, "status");
        if (Integer.parseInt(status) == 0) {
            // 解析正确
            HashMap hm = (HashMap) JsonUtil.getMap4Json(jsonResult);
            HashMap hm1 = (HashMap) JsonUtil.getMap4Json(hm.get("result") + "");
            HashMap hm2 = (HashMap) JsonUtil.getMap4Json(hm1.get("addressComponent") + "");

            // System.out.println(hm2.get("province") + "," + hm2.get("city") +
            // "," + hm2.get("district"));
            return hm2;
        } else {
            return null;
        }
    }

    public static String requestSend(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 性能测试结果:100次,共耗时:11秒 100次,共耗时:9.796秒
     * 
     * @param args
     */
    public static void main(String[] args) {
        // xntest();
        // getAddrByBDZB("39.897445", "116.331398");
        DecimalFormat df = new DecimalFormat("0");
        double distance = getDistance("39.913468", "116.316465", "28.213478", "112.979353");
        System.out.println(df.format(distance));
    }

    private static void xntest() {
        System.out.println("开始...");
        long l1 = System.currentTimeMillis();
        System.out.println(l1);
        int n = 100;
        for (int i = 0; i < n; i++) {
            double distance = getDistance("39.913468", "116.316465", "39.982208", "116.34177");
            // System.out.println(distance);

        }
        long l2 = System.currentTimeMillis();
        System.out.println(l2);
        System.out.println(n + "次,共耗时:" + (l2 - l1) / 1000.0 + "秒,平均单次耗时:" + (l2 - l1) / 1000.0 / n + "秒");
        System.out.println("结束...");
    }
}
